import { AuthenticationError } from 'apollo-server';

const jwt = require('jsonwebtoken')
const fs = require('fs')
/**
 * RS256
 * 用 RS256 算法生成与验证 JWT
 * ssh-keygen -t rsa -b 2048 -f private.key
 * openssl rsa -in private.key -pubout -outform PEM -out public.key
 */

//获取密钥
const privateKey = fs.readFileSync(__dirname+'/ssl/rsa_private_key.pem')

//获取公钥
const publicKey = fs.readFileSync(__dirname+'/ssl/rsa_public_key.pem')

  //签发 token
export async function signToken(data){
  let created = Math.floor(Date.now() / 1000);
  return jwt.sign({
    data,
    iss: '',
    version: '1.0.0',
    author: 'sandune',
    exp: created + 10 * 6000 * 60 * 2
  },privateKey,{ algorithm: 'RS256' })
}

export async function verifyToken(req){
  var token = req['x-token'] ? req['x-token'] : req.headers['x-token'];
  if(token){
      //验证 token
    let result = jwt.verify(token, publicKey, (error, decoded) => {
      if(error) {
          //TokenExpiredError
          throw new AuthenticationError('TokenExpiredError')
      }
      return decoded
    }) || {};
    let {exp = 0} = result, current = Math.floor(Date.now()/1000);

    if(current <= exp){
        return result.data || {}
    }else{
      throw new AuthenticationError(
        '登录过期，请重新登录！'
      )
    }
  }
}
